package com.starblink.brand.ui

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.skydoves.balloon.balloon
import com.starblink.android.basic.adapter.MutableAdapter
import com.starblink.android.basic.base.fragment.BaseTVMFragment
import com.starblink.android.basic.ext.visibleOrGone
import com.starblink.android.basic.extension.dp2px
import com.starblink.android.basic.extension.lazyOnNone
import com.starblink.android.basic.sensorsdata.spm.cfg.SpmPageDef
import com.starblink.android.basic.user.UserDataCenter
import com.starblink.android.basic.util.bus.FlowBus
import com.starblink.android.basic.util.bus.FlowConst
import com.starblink.basic.style.view.recyclerview.SimpleGapItemDecor
import com.starblink.basic.util.FastUtil
import com.starblink.basic.util.ScreenUtils
import com.starblink.brand.R
import com.starblink.brand.adapter.BrandDecorCell
import com.starblink.brand.adapter.BrandLeftCell
import com.starblink.brand.adapter.BrandMoreEndCell
import com.starblink.brand.adapter.BrandRightCell
import com.starblink.brand.bean.BrandLeftBean
import com.starblink.brand.databinding.CellBrandItemdecorBinding
import com.starblink.brand.databinding.CellBrandLeftBinding
import com.starblink.brand.databinding.FragmentDiscountedBinding
import com.starblink.brand.model.BrandAllVM
import com.starblink.brand.ui.part.BrandAllSort
import com.starblink.brand.widget.BrandAllBalloonFactory

class DiscountedFragment : BaseTVMFragment<FragmentDiscountedBinding,BrandAllVM>(),DiscountedI {
    private val balloon  by  balloon<BrandAllBalloonFactory>()
    private var brandAllSort:BrandAllSort?=null
    lateinit var rvLeftLayoutManager:LinearLayoutManager
    lateinit var rvRightLayoutManager:LinearLayoutManager
    private var filterType:Int=1 //0-不选中 1-全部 2-仅订阅
    private var sortType:Int=0 //0-默认排序 4-折扣从高到低 5-折扣从低到高 Discount 升降序类型
    var firstVisibleItem:Int=0 //第一个可见的item位置
    private val leftBrandAdapter by lazyOnNone {
        MutableAdapter(viewModel.brandLeftList).apply {
            addVhDelegate {
                BrandLeftCell(CellBrandLeftBinding.inflate(layoutInflater,it,false),this@DiscountedFragment)
            }
            addVhDelegate {
                BrandDecorCell(CellBrandItemdecorBinding.inflate(layoutInflater,it,false))
            }
        }
    }

    private val rightBrandAdapter by lazyOnNone {
        MutableAdapter(viewModel.brandRightList).apply {
            addVhDelegate {
                BrandRightCell(SpmPageDef.BrandAllPage,mActivity,it,0){ position->
                    if(viewModel.hasNext&&position==viewModel.brandRightList.size-3){
                        //自动加载更多
                        viewModel.reqFetchTopBrandSaleList(filterType,sortType,initData =false)
                    }
                }
            }
            addVhDelegate {
                BrandMoreEndCell(CellBrandItemdecorBinding.inflate(layoutInflater,it,false))
            }
        }
    }

    companion object {
        fun obtainFragment(): DiscountedFragment {
            return DiscountedFragment()
        }
    }

    override fun getViewBinding(
        inflater: LayoutInflater,
        container: ViewGroup?
    ): FragmentDiscountedBinding {
        return FragmentDiscountedBinding.inflate(inflater, container, false)
    }

    override fun startObserve() {
        FlowBus.with<Boolean>(FlowConst.LOGIN_STATUS_CHANGE).register(this) {
            viewModel.reqFetchTopBrandSaleList(filterType,sortType,initData = true, ifShowLoading = true)
        }

        viewModel.topBrandSaleList.observe(this) {
            viewBinding.rvLeftBrand.visibleOrGone(true)
            viewBinding.llRightBrand.visibleOrGone(true)
            if (viewModel.pageNo == 1) {
                //首页 滑动顶部
                viewBinding.rvLeftBrand.scrollToPosition(0)
                viewBinding.rvRightBrand.scrollToPosition(0)
            }
            val indexTag = viewModel.brandRightList.size
            //获取当前列表数量后再添加数据进行局部刷新
            viewModel.addBrandList()
            val endTag=viewModel.brandRightList.size-indexTag
            if (indexTag == 0) {
                rightBrandAdapter.refreshAll()
                leftBrandAdapter.refreshAll()
            } else {
                rightBrandAdapter.notifyItemRangeInserted(indexTag, endTag)
                leftBrandAdapter.notifyItemRangeInserted(indexTag, endTag)
            }

            if(viewBinding.smartRefreshLayout.isRefreshing){
                viewBinding.smartRefreshLayout.finishRefresh()
            }
            if (viewBinding.smartRefreshLayout.isLoading) {
                viewBinding.smartRefreshLayout.finishLoadMore()
            }
            if(viewModel.brandLeftList.isNotEmpty()){
                //首次进入默认是隐藏的 loading完显示一次就可
                viewBinding.llRightFilter.visibleOrGone(true)
            }

            //无数据显示empty
            viewBinding.empty.visibleOrGone(viewModel.brandLeftList.isEmpty()&&!viewModel.hasNext) {
                viewBinding.rvLeftBrand.visibleOrGone(false)
                viewBinding.llRightBrand.visibleOrGone(false)

                viewBinding.empty.btnShown = true
                viewBinding.empty.btnText = "View All Discounted Brands"
                viewBinding.empty.onBtnClick = {
                    //状态回执
                    filterType = 1
                    viewBinding.btnAll.setTextAppearance(context,com.starblink.basic.style.R.style.SimpleMaterialButton_Label_M)
                    viewBinding.btnAll.setTextColor(resources.getColor(com.starblink.basic.style.R.color.gu_text_primary))

                    sortType = 0
                    viewBinding.btnSort.setIconResource(R.mipmap.icon_branch_sort)
                    viewBinding.btnSort.setTextAppearance(context,com.starblink.basic.style.R.style.SimpleMaterialButton_Body_M)
                    viewBinding.btnSort.setTextColor(resources.getColor(com.starblink.basic.style.R.color.gu_text_secondary))

                    viewModel.reqFetchTopBrandSaleList(filterType,sortType,initData = true, ifShowLoading = true)
                }
            }
        }
    }

    override fun initData() {
        viewBinding.smartRefreshLayout.setEnableRefresh(true)
        viewBinding.smartRefreshLayout.setOnRefreshListener {
            viewModel.reqFetchTopBrandSaleList(filterType,sortType,initData =true)
        }
        viewBinding.smartRefreshLayout.setEnableLoadMore(true)
        viewBinding.smartRefreshLayout.setOnLoadMoreListener {
            //已经有上拉自动加载 这里不再触发接口请求
            viewBinding.smartRefreshLayout.finishLoadMore(500)
        }

        rvLeftLayoutManager= LinearLayoutManager(requireContext())
        rvRightLayoutManager= LinearLayoutManager(requireContext())

        viewBinding.rvLeftBrand.layoutManager = rvLeftLayoutManager
        viewBinding.rvLeftBrand.adapter = leftBrandAdapter
        viewBinding.rvLeftBrand.addItemDecoration(
            SimpleGapItemDecor(
                horGap = 0.dp2px(),
                verGap = 0.dp2px()
            )
        )

        viewBinding.rvRightBrand.layoutManager = rvRightLayoutManager
        viewBinding.rvRightBrand.adapter = rightBrandAdapter
        viewBinding.rvRightBrand.addItemDecoration(
            SimpleGapItemDecor(
                horGap = 0.dp2px(),
                verGap = 0.dp2px()
            )
        )

        viewBinding.btnAll.setOnClickListener {
            showSortPopup(it)
        }
        viewBinding.btnSort.setOnClickListener {
            //Discount 升降序类型
            when (sortType) {
                0 -> {
                    sortType = 4
                    viewBinding.btnSort.setIconResource(R.mipmap.icon_branch_sort_down)
                    viewBinding.btnSort.setTextAppearance(context,com.starblink.basic.style.R.style.SimpleMaterialButton_Label_M)
                    viewBinding.btnSort.setTextColor(resources.getColor(com.starblink.basic.style.R.color.gu_text_primary))

                    //互斥
                    if(filterType==1){
                        filterType = 0
                        viewBinding.btnAll.setTextAppearance(context,com.starblink.basic.style.R.style.SimpleMaterialButton_Body_M)
                        viewBinding.btnAll.setTextColor(resources.getColor(com.starblink.basic.style.R.color.gu_text_secondary))
                    }

                }
                5 -> {
                    sortType = 0
                    viewBinding.btnSort.setIconResource(R.mipmap.icon_branch_sort)
                    viewBinding.btnSort.setTextAppearance(context,com.starblink.basic.style.R.style.SimpleMaterialButton_Body_M)
                    viewBinding.btnSort.setTextColor(resources.getColor(com.starblink.basic.style.R.color.gu_text_secondary))

                    //状态回执
                    if(filterType == 0){
                        filterType = 1
                        viewBinding.btnAll.setTextAppearance(context,com.starblink.basic.style.R.style.SimpleMaterialButton_Label_M)
                        viewBinding.btnAll.setTextColor(resources.getColor(com.starblink.basic.style.R.color.gu_text_primary))
                    }

                }
                4 -> {
                    sortType = 5
                    viewBinding.btnSort.setIconResource(R.mipmap.icon_branch_sort_up)
                    viewBinding.btnSort.setTextAppearance(context,com.starblink.basic.style.R.style.SimpleMaterialButton_Label_M)
                    viewBinding.btnSort.setTextColor(resources.getColor(com.starblink.basic.style.R.color.gu_text_primary))
                }
            }
            viewModel.reqFetchTopBrandSaleList(filterType,sortType,initData =true, ifShowLoading = true)
        }

        //监听滑动事件
        viewBinding.rvRightBrand.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                super.onScrollStateChanged(recyclerView, newState)
                when (newState) {
                    RecyclerView.SCROLL_STATE_IDLE -> {
                        //当屏幕停止滚动 需要联动
                        changeBrandState(firstVisibleItem)
                    }
                }
            }

            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                //获取首个展示和最后一个展示项
                firstVisibleItem =
                    rvRightLayoutManager.findFirstCompletelyVisibleItemPosition()
                val lastVisibleItem =
                    rvRightLayoutManager.findLastCompletelyVisibleItemPosition()

                changeBrandState(firstVisibleItem,true)
            }
        })

        viewModel.reqFetchTopBrandSaleList(filterType,sortType,initData = true, ifShowLoading = true)
    }

    //显示筛选弹框
    private fun showSortPopup(view: View){
        if(brandAllSort==null) {
            brandAllSort = BrandAllSort(context,balloon){
                //类型：1-全部 2-仅订阅
                filterType=it
                viewBinding.btnAll.setTextAppearance(context,com.starblink.basic.style.R.style.SimpleMaterialButton_Label_M)
                viewBinding.btnAll.setTextColor(resources.getColor(com.starblink.basic.style.R.color.gu_text_primary))
                when (filterType) {
                    1 -> {
                        viewBinding.btnAll.text = "Recommended"

                        //与Discount 互斥
                        sortType=0
                        viewBinding.btnSort.setIconResource(R.mipmap.icon_branch_sort)
                        viewBinding.btnSort.setTextAppearance(context,com.starblink.basic.style.R.style.SimpleMaterialButton_Body_M)
                        viewBinding.btnSort.setTextColor(resources.getColor(com.starblink.basic.style.R.color.gu_text_secondary))
                    }
                    2 -> {
                        viewBinding.btnAll.text = "Following Brands"
                    }
                }
                viewModel.reqFetchTopBrandSaleList(filterType,sortType,initData =true, ifShowLoading = true)
            }.apply {
                handleVM()
            }
        }
        brandAllSort?.setType(filterType)
        balloon.showAlignBottom(view)
    }

    //联动
    private fun changeBrandState(position:Int,ifScroll:Boolean=false){
        if(ifScroll&&FastUtil.isFast()){
            //快速时略过
            return
        }
        viewModel.brandLeftList.mapIndexed { index, item ->
            //只修改状态变化的item
            if(item is BrandLeftBean && index==position&&!item.selected){
                item.selected=true
                leftBrandAdapter.notifyItemRangeChanged(index,1)
                rvLeftLayoutManager.scrollToPositionWithOffset(index, 40)
            }
            if(item is BrandLeftBean && item.selected&&index!=position){
                item.selected=false
                leftBrandAdapter.notifyItemRangeChanged(index,1)
            }
        }
    }

    override fun scrollToBrand(position: Int) {
        //联动
        rvRightLayoutManager.scrollToPositionWithOffset(position, 0)
        changeBrandState(position)
    }

}

interface DiscountedI{
    fun scrollToBrand(position:Int)//点击Left后滚动到指定位置
}